<template>
    <van-list class="product-list" v-model="loading" :finished="!loading">
        <van-empty class="product-list-empty" image="search" description="没有找到相关的产品" v-if="emptyProducts && loaded"/>
        <div class="product-list-content" v-else>
            <product-list-item v-for="product in products" :key="product.id" :product="product"/>
        </div>
    </van-list>
</template>

<script>
  import * as _ from "lodash"
  import ProductListItem from "@/components/product/ProductListItem"
  import { Col, Empty, List, Row } from "vant"
  import { catalog } from "@mall/api-services"

  export default {
    name: "ProductList",
    components: {
      ProductListItem,
      [Col.name]: Col,
      [Empty.name]: Empty,
      [List.name]: List,
      [Row.name]: Row,
    },
    props: {
      name: String,
      storeId: String,
      collections: [String, Array],
      sort: String,
    },
    watch: {
      sort() {
        this.refreshProducts()
      },
      name() {
        this.refreshProducts()
      },
    },
    computed: {
      loaded() {
        return !this.loading
      },
      emptyProducts() {
        const { products } = this
        return _.isEmpty(products)
      },
    },
    data() {
      return {
        loading: false,
        products: [],
      }
    },
    created() {
      this.refreshProducts()
    },
    methods: {
      refreshProducts() {
        const { storeId, collections, sort, name } = this
        this.loading = true
        catalog.ProductServiceV1
          .getProducts()
          .storeId(storeId)
          .name(name)
          .collections(collections)
          .sort(sort)
          .list()
          .then(pageProducts => this.products = pageProducts.elements)
          .finally(() => {
            this.loading = false
          })
      },
    },
  }
</script>

<style lang="scss" scoped>
    .product-list {
        .product-list-content {
            padding: 4px;
            display: flex;
            flex-wrap: wrap;
        }

        .product-list-empty {
            margin: 100px auto 0 auto;
        }
    }

</style>
